<template>
  <div class="reg">
    <!-- el-card就是类选择器 -->
    <el-card class="box-card">
      <!-- 标题 -->
      <div class="title"></div>
      <!-- 放表单 -->
      <el-form ref="form" :model="user" :rules="rules">
        <!-- 表单里面的每一项  prop="username"要跟rules里面的每一项对应-->
        <el-form-item prop="username">
          <el-input v-model="user.username" prefix-icon="el-icon-user"> </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="user.password" prefix-icon="el-icon-lock" show-password></el-input>
        </el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form>
      <el-link :underline="false" @click="$router.push('/reg')">没有账号，去注册</el-link>
    </el-card>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'MyReg',
  data() {
    return {
      user: {
        username: '',
        password: ''
      },
      // 这里写对上面每一项的验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      // 点击登录是还要将整个表单进行一次验证，看是否都填
      // valid 就是验证所有表单是否都通过验证，如果通过验证就返回true，那么我们就可以去发送post请求
      // 否则的话就注册不了
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const { data: res } = await loginAPI(this.user)
        if (res.code === 0) {
          // （1）登录成功后要将提示
          this.$message.success(res.message)
          // （2）登录成功后将token保存到vuex中
          this.$store.commit('user/updateToken', res.token)
          // (3)跳转到首页
          this.$router.push('/')
        } else {
          // 登录失败后要将提示
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.reg {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin: 0;
  padding: 0;
  background: url('@/assets/images/login_bg.jpg') no-repeat center center;
  background-size: cover;
  .el-card {
    width: 400px;
    // height: 400px;
    .title {
      height: 50px;
      background: url('@/assets/images/login_title.png') no-repeat top center;
    }
    .el-button {
      width: 100%;
      margin-bottom: 10px;
    }
  }
}
</style>
